import logging
import random

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.utils.captcha.captcha import captcha
from verifications import constants
logger = logging.getLogger('django')

class SMSCodeView(APIView):
    """
    生成短信验证码的视图函数
    """
    def get(self,request,mobile):
        """
        1.随机生成６位数字作为短信验证码
        2.在redis中存储短信验证码内容，以sms_<mobile>为key,验证码内容为value
        3.使用云通讯给mobile发送短信
        4.返回应答给前端，短信发送成功
        """

        # 判断６０ｓ内是否给mobile发送过短信
        redis_conn = get_redis_connection('verify_codes')
        reso = redis_conn.get('flag_%s'%mobile)
        if reso:
            return Response({"message": "请求次数过于频繁"}, status=status.HTTP_400_BAD_REQUEST)
        # 1.
        # 随机生成６位数字作为短信验证码
        sms_code = '%06d'%random.randint(0,999999)
        print('短信验证码：%s'% sms_code)
        # 2.
        # 在redis中存储短信验证码内容，以sms_ < mobile > 为key, 验证码内容为value

        # redis_conn.setex('<key>','<expires>','<value>')
        # redis_conn.set('<key>','<value>',"<expires>")
        # 1.采用redis管道节省连接redis的时间
        pl = redis_conn.pipeline()
        # 2. 创建管道对象后，创建redis任务
        # redis_conn.setex('sms_%s'% mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # redis_conn.setex('flag_%s'% mobile,constants.SMS_CODE_INTERVAL,1)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('flag_%s' % mobile, constants.SMS_CODE_INTERVAL, 1)
        # 3.一次性执行管道任务
        pl.execute()
        3.# 使用云通讯给mobile发送短信
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        # 发出发送短信任务信息
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code,expires)
        # try:
        #     res = CCP().send_template_sms(mobile,[sms_code,expires],constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error(e)
        #     return Response({"message": "发送短信异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        #
        # if res != 0:
        #     # logger.error('Error Message')
        #     return Response({"message": "发送短信失败"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4.
        # 返回应答给前端，短信发送成功
        return Response({"message": "OK"})


# GET /image_code
class ImageCodeGenerateView(APIView):
    # 生成图片验证码
    def get(self, request, img_uuid):
        redis_conn = get_redis_connection('verify_codes')
        id, value, img_bytes=captcha.generate_captcha()
        redis_conn.setex('img_code_%s' % img_uuid, constants.IMAGE_CODE_EXPIRES, value)
        resp = Response(content_type='image/png')
        resp.content = img_bytes
        return resp




